import React, { useReducer, useEffect } from "react";
import "./Cate.css";
import { initState, reducer, actions } from "./cate";
import { reqGetcate, reqGetgoods, reqCartadd } from "../../request/api";
const Cate = (props) => {
  const [state, dispatch] = useReducer(reducer, initState);
  let { cate,goods, } = state;
  //进来页面
  useEffect(() => {
    reqGetcate().then((res) => {
      if (res.data.code === 200) {
        //存信息
        dispatch(actions.changeCate(res.data.list));
      }
    });
    //分类商品
    Getgoods(1)
    
    
}, []);
//购物车添加
let Cartadd = (goodsid) => {
    let uid=JSON.parse(sessionStorage.getItem('info')).uid;
    reqCartadd({uid:uid,goodsid:goodsid,type:1,num:1}).then((res) => {
        if(res.data.code===200){
             //存信息
          dispatch(actions.changeCartadd(res.data.list))
        }
    });
  }
  //分类商品
  let Getgoods=(id)=>{
    reqGetgoods({fid:id}).then((res) => {
        if(res.data.code===200){
             //存信息
          dispatch(actions.changeGoods(res.data.list))
        }
    });
  }
  return (
    <div className="cate">
    <ul className="cate_ul">
      {cate? cate.map((item) => 
        <li key={item.id} onClick={()=>Getgoods(item.id)}
      
        >{item.catename}</li>)
        : null}
    </ul>
    <div className="cate_right">
      <h3>热门精选</h3>
      {goods? goods.map((item) => (
            <div className="cate_right_box" key={item.id}>
              <img src={item.img} alt="" />
             <div className='cate_you'>
               <div>{item.goodsname}</div>
              <div>现价：{item.price}</div>
              <div>原价：{item.market_price}</div>
             </div>
             <button onClick={()=>Cartadd(item.id)}>加入购物车</button>
            </div>
          ))
        : null}
    </div>
  </div>
  )
};

export default Cate;
